const { get, put, delete: del } = require('../../../utils/request');
const { COLLECT_API } = require('../../../utils/api');

Page({
  data: {
    // 页面参数
    folderId: '',
    folderName: '',
    folderType: '',
    // 菜谱列表
    recipeList: [],
    // 加载状态
    loading: false,
    // 新增弹窗相关数据
    showEditModal: false,
    newFolderName: ""
  },

  // 页面加载时接收参数
  onLoad(options) {
    console.log('FolderCookbook页面接收到的参数:', options);
    
    if (options.id) {
      this.setData({
        folderId: options.id,
        folderName: options.name || '收藏夹',
        folderType: options.type || 'food'
      });
      
      // 设置页面标题
      wx.setNavigationBarTitle({
        title: options.name || '收藏夹'
      });
      
      // 根据ID获取收藏夹内容
      this.getFolderContent(options.id);
    }
  },

  // 获取收藏夹内容
  async getFolderContent(collectionsId) {
    try {
      console.log('获取收藏夹内容，ID:', collectionsId);
      this.setData({ loading: true });
      
      const url = `${COLLECT_API.COLLECTION_RECIPES}/${collectionsId}`;
      const result = await get(url);
      console.log('API返回结果:', result);
      
      if (result && result.data && result.data.length > 0) {
        // 处理API返回的数据，确保格式正确
        const processedData = result.data.map(item => ({
          id: item.id || item.recipeId || Math.random().toString(36).substr(2, 9),
          title: item.title || item.recipeName || item.name || '未知菜谱',
          time: item.cookTimeName || '15-30分钟',
          skill: item.difficultyName || '简单',
          avatar: item.authorAvatar || item.avatar || '/images/user0.png',
          author: item.authorName || item.author || '未知作者',
          coverUrl: item.coverUrl || item.imageUrl || '/images/FolderCookbook.png'
        }));
        
        this.setData({
          recipeList: processedData,
          loading: false
        });
        console.log('设置菜谱列表数据:', this.data.recipeList);
      } else {
        console.log('API返回数据为空或格式不正确');
        this.setData({ 
          recipeList: [],
          loading: false 
        });
        
        wx.showToast({
          title: '暂无菜谱数据',
          icon: 'none',
          duration: 2000
        });
      }
    } catch (error) {
      console.error('获取收藏夹菜谱列表失败:', error);
      this.setData({ 
        recipeList: [],
        loading: false 
      });
      
      // 如果API请求失败，显示默认数据
      this.setDefaultData();
      
      wx.showToast({
        title: '获取数据失败，显示默认内容',
        icon: 'none',
        duration: 2000
      });
    }
  },

  // 设置默认数据（当API请求失败时使用）
  setDefaultData() {
    const defaultData = [
      {
        id: '1',
        title: "新手必学阳春面",
        time: "15-30分钟",
        skill: "零厨艺",
        avatar: "/images/user0.png", 
        author: "不会做饭的西瓜",
        coverUrl: "/images/FolderCookbook.png"
      },
      {
        id: '2',
        title: "新手必学阳春面",
        time: "15-30分钟",
        skill: "零厨艺",
        avatar: "/images/user0.png",
        author: "不会做饭的西瓜",
        coverUrl: "/images/FolderCookbook.png"
      },
      {
        id: '3',
        title: "新手必学阳春面",
        time: "15-30分钟",
        skill: "零厨艺",
        avatar: "/images/user0.png",
        author: "不会做饭的西瓜",
        coverUrl: "/images/FolderCookbook.png"
      },
      {
        id: '4',
        title: "新手必学阳春面",
        time: "15-30分钟",
        skill: "零厨艺",
        avatar: "/images/user0.png",
        author: "不会做饭的西瓜",
        coverUrl: "/images/FolderCookbook.png"
      }
    ];
    
    this.setData({
      recipeList: defaultData
    });
    console.log('设置默认菜谱数据:', this.data.recipeList);
  },
  
  GoToRecipe(e){
    const itemId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/recipeDetail/recipeDetail', // 假设的菜谱详情页路径
    })
  },
  
  GoToUser(e){
    const userId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/userProfile/userProfile', // 假设的用户主页路径
    })
  },
  
  showActionSheet() {
    wx.showActionSheet({
      itemList: ["编辑名称", "删除文件夹"],
      itemColor: "#333",
      success: (res) => {
        if (res.tapIndex === 0) {
          // 编辑名称 - 显示弹窗
          this.setData({
            showEditModal: true,
            newFolderName: "" // 重置输入框
          });
        } else if (res.tapIndex === 1) {
          // 删除文件夹
          this.showDeleteConfirm();
        }
      },
      fail: (err) => {
        console.log("操作菜单失败：", err);
      }
    });
  },
  
  // 输入框内容变化时触发
  onNameInput(e) {
    this.setData({
      newFolderName: e.detail.value
    });
  },
  
  // 隐藏编辑弹窗
  hideEditModal() {
    this.setData({
      showEditModal: false
    });
  },
  
  // 确认修改名称
  async confirmEditName() {
    const newName = this.data.newFolderName.trim();
    if (!newName) {
      wx.showToast({
        title: "名称不能为空",
        icon: "none"
      });
      return;
    }
    
    try {
      // 组装请求对象
      const requestData = {
        name: newName,
        id: this.data.folderId
      };
      
      console.log('修改收藏夹名称，请求数据:', requestData);
      
      // 调用PUT接口修改收藏夹名称
      const result = await put(COLLECT_API.UPDATE_COLLECTION, requestData);
      console.log('修改收藏夹名称成功:', result);
      
      // 修改成功后更新页面数据
      this.setData({
        folderName: newName,
        showEditModal: false
      });
      
      // 更新页面标题
      wx.setNavigationBarTitle({
        title: newName
      });
      
      wx.showToast({
        title: "修改成功",
        icon: "success"
      });
      
      console.log("新的收藏夹名称：", newName);
      
    } catch (error) {
      console.error('修改收藏夹名称失败:', error);
      wx.showToast({
        title: "修改失败，请稍后重试",
        icon: "none",
        duration: 2000
      });
    }
  },
  
  // 显示删除确认
  showDeleteConfirm() {
    wx.showModal({
      title: "删除提示",
      content: "确定删除文件夹所有收藏的菜谱？删除后将无法恢复。",
      success: (res) => {
        if (res.confirm) {
          // 调用删除接口
          this.deleteCollection();
        }
      }
    });
  },

  // 删除收藏夹
  async deleteCollection() {
    try {
      console.log('删除收藏夹，ID:', this.data.folderId);
      
      // 调用DELETE接口删除收藏夹
      const result = await del(`${COLLECT_API.DELETE_COLLECTION}/${this.data.folderId}`);
      console.log('删除收藏夹成功:', result);
      
      wx.showToast({
        title: "删除成功",
        icon: "success",
        duration: 1500
      });
      
      // 延迟跳转，让用户看到成功提示
      setTimeout(() => {
        // 跳转回favorites页面并刷新列表
        wx.redirectTo({
          url: '/collect/pages/favorites/favorites',
          success: () => {
            console.log('跳转回favorites页面成功');
          },
          fail: (err) => {
            console.error('跳转回favorites页面失败:', err);
            // 如果跳转失败，尝试使用navigateBack
            wx.navigateBack({
              delta: 1
            });
          }
        });
      }, 1500);
      
    } catch (error) {
      console.error('删除收藏夹失败:', error);
      wx.showToast({
        title: "删除失败，请稍后重试",
        icon: "none",
        duration: 2000
      });
    }
  },

  // 下拉刷新
  onPullDownRefresh() {
    if (this.data.folderId) {
      this.getFolderContent(this.data.folderId).then(() => {
        wx.stopPullDownRefresh();
      });
    } else {
      wx.stopPullDownRefresh();
    }
  }
})
    